package cn.ubeta.b2c.utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by denny on 16/4/3.
 */
public class JsonUtils {

    /**
     * 从字符串构建
     * @param json
     * @return
     */
    public static JSONArray JSONArrayFrom(String json) {
        if (json != null) {
            try {
                return new JSONArray(json);
            } catch (JSONException ignored) {
            }
        }
        return null;
    }

    /**
     * 从数组获取对象
     * @param obj
     * @param index
     * @return
     */
    public static JSONObject getJSONObject(JSONArray obj, int index) {
        if (obj != null) {
            try {
                return obj.getJSONObject(index);
            } catch (JSONException ignored) {
            }
        }
        return null;
    }

    /**
     * 获取数组
     * @param obj
     * @param key
     * @return
     */
    public static  JSONArray getJSONArray(JSONObject obj, String key) {
        if (obj != null) {
            try {
                return obj.getJSONArray(key);
            } catch (JSONException ignored) {
            }
        }
        return null;
    }

    /**
     * 判断JSON数组是否为空
     *
     * @param array
     * @return
     */
    public static boolean isEmpty(JSONArray array) {
        return (array == null || array.length() == 0);
    }

    /**
     * 读取字符串
     * @param obj
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getString(JSONObject obj, String key, String defaultValue) {
        String temp = defaultValue;
        if (obj != null && obj.has(key)) {
            try {
                temp = obj.getString(key);
            } catch (JSONException ignored) {
            }
        }
        return temp;
    }

    /**
     * 读取int
     */
    public static int getInt(JSONObject obj, String key, int defaultValue) {
        int temp = defaultValue;
        if (obj == null || !obj.has(key)) {
            return temp;
        }
        try {
            temp = obj.getInt(key);
        } catch (JSONException ignored) {
        }
        return temp;
    }

    /**
     * 从json串中获取指定key的值
     * @param json
     * @param key
     * @return
     */
    public static String getString(String json, String key) {
        try {
            JSONObject obj = new JSONObject(json);
            return obj.getString(key);
        } catch (JSONException ignored) {
        }
        return null;
    }

    /**
     * 从json串中获取指定key的值
     * @param json
     * @param key
     * @return
     */
    public static int getInt(String json, String key) {
        try {
            JSONObject obj = new JSONObject(json);
            return obj.getInt(key);
        } catch (JSONException ignored) {
        }
        return -1;
    }
}
